# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required

import urllib
from .saltapi import salt
from .models import Minion, MinionDetail, Server
from saltops.forms import PaginationForm

def query(req):
    form = PaginationForm(req.GET)
    if not form.is_valid():
        pass
    params = form.getPaginationParams()
    limit   = params['limit']
    offset  = params['offset']
    sort    = params['sort']
    order   = params['order']
    ## 只查看已接受的minion节点(其他类型的节点没有有用信息)
    minions = Minion.objects.filter(type = 0).all()
    result = {'rows': [], 'total': minions.count()}
    minions = minions[offset: offset + limit]
    for minion in minions:
        minionInfo = minion.parse()
        if minionInfo['status']:
            hwareId = minion.miniondetail.hware_id
            exists = Server.objects.filter(hware_id = hwareId).exists()
            if exists:
                server = Server.objects.get(hware_id = hwareId)
                minionInfo['bussiness'] = server.bussiness
                minionInfo['project'] = server.project
                minionInfo['IPs'] = server.ips
        result['rows'].append(minionInfo)
    return JsonResponse(result)
